package org.chnxi.datastructures.stack;

/**
 * 使用数组模拟栈
 */
public class ArrayStack<E> {

    ArrayStack(int size){
        this.maxSize = size;
        this.stack = (E[]) new Object[maxSize];
    }

    //栈的大小
    private int maxSize;

    //数组，模拟栈
    private E[] stack;

    //表示栈顶
    private int top = -1;

    /**
     * 判断栈是否满了
     * @return
     */
    public boolean isFull(){
        return top == maxSize - 1;
    }

    /**
     * 判断栈是否空
     * @return
     */
    public boolean isEmpty(){
        return top == -1;
    }

    /**
     * 入栈
     * @param
     */
    public void push(E e){
        if(isFull()){
            System.out.println("栈满了");
            return;
        }
        top++;
        stack[top] = e;
    }

    /**
     * 出栈
     * @return
     */
    public E pop(){
        if(isEmpty()){
            System.out.println("栈空了");
            throw new RuntimeException("栈空了");
        }
        E e = stack[top];
        top--;
        return e;
    }

    /**
     * 遍历，需要从栈顶开始输出
     */
    public void list(){
        if(isEmpty()){
            System.out.println("栈空的");
            return;
        }
        for (int i = top ; i >=0 ; i--){
            System.out.println(stack[i]);
        }
    }

}
